<template>
    <div class="comment">
      <h4>发表评论---{{ id }}</h4>
      <hr />
      <textarea name="" id="com-text" maxlength="120" placeholder="请输入要BB的内容（最多吐槽120字）" v-model="msg"></textarea>
      <mt-button type="primary" size="large" @click="addClick()">发表评论</mt-button>
      <div class="comment-text" v-for="(v, k) in commentList" :key="k">
        <div class="comment-hd">
          第{{ k + 1 }}楼 用户：{{ v.user_name }} 发表时间：{{ v.add_time | timeFormat }}
        </div>
        <div class="comment-bd">
          {{ v.content === '' ? '此人很懒，什么都没留下' : v.content }}
        </div>
      </div>
      <!-- 加载更多 -->
      <mt-button plain type="danger" size="large" @click="moreClick()">加载更多</mt-button>
    </div>
</template>

<script>
import { Toast } from 'mint-ui'
export default {
  props: ['id'],
  created() {
    this.getCommentsList()
  },
  data() {
    return {
      // 评论数据
      commentList: [],
      // 加载更多
      pageindex: 1,
      // 评论内容
      msg: ''
    }
  },
  methods: {
    // 发表评论
    async addClick() {
      if (this.msg.trim().length === 0) {
        return Toast('请填写评论内容！')
      }
      // console.log(text)
      const {data: dt} = await this.$http.post(`/api/postcomment/${this.id}`, {content: this.msg.trim()})
      // console.log(dt)
      var cmt = {
        user_name: '匿名用户',
        add_time: Date.now(),
        content: this.msg.trim()
      }
      this.commentList.unshift(cmt)
      this.msg = ''
    },
    // 获取评论
    async getCommentsList() {
      // console.log(this.id)
      const {data: dt} = await this.$http.get(`/api/getcomments/${this.id}?pageindex=${this.pageindex}`)
      console.log(dt)
      //! 将新获取的评论数组和之前获取的评论合并，否则只会显示新获取的评论，就评论会被覆盖
      this.commentList = this.commentList.concat(dt.message)
    },
    // 加载更多评论
    moreClick() {
      this.pageindex++
      // console.log(this.pageindex)
      this.getCommentsList()
    }
  }
}
</script>

<style scoped>
.comment {
  font-size: 14px;
}
.comment textarea {
  font-size: 14px;
  margin: 0;
}
.comment-hd {
  background-color: #ddd;
}
.comment-bd {
  text-indent: 2em;
  font-size: 13px;
}
.mint-button {
  margin: 5px 0;
}
</style>
